package drawing 
{
	import app.textures.TextureInfo;
	import app.textures.TextureInfoGroupe;
	import flash.utils.Dictionary;
	import resources.TextureParts;
	import utils.Logger;
	/**
	 * ...
	 * @author Dmitriy Gaiduk
	 */
	public class PaletteManager 
	{
		private var _paletteDictionary:Dictionary;
		
		private static var _instance:PaletteManager;
		
		private var _textureParts:TextureParts;
		
		public function PaletteManager() 
		{
			_paletteDictionary = new Dictionary();
			_textureParts = new TextureParts();
		}
		
		public static function getInstance():PaletteManager
		{
			if (_instance == null)
			{
				_instance = new PaletteManager();
			}
			return _instance;
		}
		
		/**
		 * 
		 * @param	textureInfo
		 * @return	palette for TextureInfo.textureType
		 */
		public  function getPalette(textureGroupe:TextureInfoGroupe,textureInfo:TextureInfo):IPalette
		{
			var key:String;
			
			if (textureGroupe.textureType == TextureInfoGroupe.TEXTURE_TYPE_COLOR)
			{
				key = textureInfo.color.toString();
			}else if (textureGroupe.textureType == TextureInfoGroupe.TEXTURE_TYPE_BITMAP)
			{
				key = textureInfo.sourceURL;
			}else if (textureGroupe.textureType == TextureInfoGroupe.TEXTURE_TYPE_SET_OF_BITMAP)
			{
				key = textureInfo.id;
			}
			
			
			if (key == null)
			{
				throw new Error("Texture key error");
				return null;
			}
			// seek exists palette
			var palette:IPalette = _paletteDictionary[key] as IPalette;
			if (palette == null)
			{
				palette = createPalette(textureGroupe, textureInfo);
				_paletteDictionary[key] = palette;	
			}
			log("key: " + key);
			return palette;
		}
		
		
		
		private function log(msg:String):void
		{
			Logger.log(this, msg);
		}
		
		private function createPalette(textureGroupe:TextureInfoGroupe, textureInfo:TextureInfo):IPalette
		{
			var palette:IPalette = null;
			switch(textureGroupe.textureType)
			{
				case TextureInfoGroupe.TEXTURE_TYPE_COLOR:
						palette = new ColorPalette(textureInfo.color);
					break;
				case TextureInfoGroupe.TEXTURE_TYPE_BITMAP:
						//_textureParts.loadTextures(textureInfo.parts);
						palette = new BitmapPalette(textureInfo.texture);
					break;
				case TextureInfoGroupe.TEXTURE_TYPE_SET_OF_BITMAP:
						_textureParts.loadTextures(textureInfo.parts);
						palette = new BitmapKitPalette(_textureParts);
					break;
			}
			return palette;
		}
		
	}

}